﻿#if !NETFRAMEWORK
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using UEditorNetCore;
using SoapCore;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.OpenApi.Models; 
using WebSelfHost.Web.WebService;
using System.IO;
using JinianNet.JNTemplate;
using WebSelfHost.Utility.Extension;
using Microsoft.AspNetCore.Http.Features; 
using System; 
using WebSelfHost.Web.Filters;

namespace WebSelfHost.Web
{
    /// <summary>
    /// Web启动类
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }


        /// <summary>
        /// 配置
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// 配置服务
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(GlobalValue.Config.SessionTimeout);
            });
            //使用缓存
            services.AddMemoryCache();
            services.AddMvc();
            //解决文件上传Request body too large
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });
            services.AddControllers();
            services.AddUEditorService("Configs/ueditor.json");


            //注册Swagger生成器，定义一个和多个Swagger 文档
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    // {ApiName} 定义成全局变量，方便修改
                    Version = "v1",
                    Title = "My API",
                    Description = "API接口调用说明",
                    Contact = new OpenApiContact
                    {
                        Name = "大师兄法号随缘",
                        Email = "xxx@qq.com",
                        Url = new System.Uri("https://www.cnblogs.com/zjwno1")
                    }
                });
                //在接口类、方法标记属性 [HiddenApi]，可以阻止【Swagger文档】生成 
                c.DocumentFilter<HiddenApiFilter>();
                c.OrderActionsBy(o => o.RelativePath);
                var basePath = System.AppDomain.CurrentDomain.BaseDirectory;//获取应用程序所在目录（绝对，不受工作目录影响，建议采用此方法获取路径）
                var xmlPath = Path.Combine(basePath, "WebSelfHost.Web.xml");
                if (File.Exists(xmlPath))
                    c.IncludeXmlComments(xmlPath);
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.TryAddSingleton<WebServiceContract>();
            //services.AddRazorPages().AddRazorRuntimeCompilation();
        }


        /// <summary>
        /// 配置
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseExceptionHandler("/index/error");
            app.UseHsts();

            //配置WebService
            app.UseSoapEndpoint<WebServiceContract>("/WebService.asmx", new SoapEncoderOptions());


            MyHttpContext.ServiceProvider = app.ApplicationServices;
            //启用Session
            app.UseSession();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            //配置模板引擎
            Engine.Configure(c =>
            {
                c.TagPrefix = "${";
                c.TagSuffix = "}";
                c.TagFlag = '^';
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
#else

using JinianNet.JNTemplate;
using Owin;
using System.Web.Http;
using System.Net.Http.Formatting;
using OwinSessionMiddleware;
using System.Web;
using System.Web.SessionState;
using Microsoft.Owin.Extensions;
using Beginor.Owin.StaticFile;
using WebSelfHost.Utility.Extension;
using Swashbuckle.Application;
using WebSelfHost.Web.Filters;
using System.Web.Http.Dispatcher;
using System.Collections.Generic;
using System.Reflection;
using System; 

namespace WebSelfHost.Web
{
    /// <summary>
    /// Web启动类
    /// </summary>
    public class Startup
    {
        private HttpConfiguration _config;
        /// <summary>
        /// 配置
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configuration(IAppBuilder app)
        {
            _config = new HttpConfiguration();
            _config.MapHttpAttributeRoutes();
            _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            _config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));
            _config
                .EnableSwagger(c =>
                {
                    //设置版本和接口描述 
                    c.SingleApiVersion("v1", "My API");
                    //在接口类、方法标记属性 [HiddenApi]，可以阻止【Swagger文档】生成 
                    c.DocumentFilter<HiddenApiFilter>();
                })
                .EnableSwaggerUi();
            var options = new SessionMiddlewareOptions
            {
                CookieName = "mySession",
                CookieLifetime = TimeSpan.FromMinutes(GlobalValue.Config.SessionTimeout)
            };
            app.UseSessionMiddleware(options);
            app.UseWebApi(_config);
            app.UseStaticFile(new StaticFileMiddlewareOptions
            {
                RootDirectory = MyEnvironment.WebRootPath(""),
                DefaultFile = "index.html",
                EnableETag = true,
                EnableHtml5LocationMode = true
            });
            //配置模板引擎
            Engine.Configure(c =>
            {
                c.TagPrefix = "${";
                c.TagSuffix = "}";
                c.TagFlag = '^';
            });
        }
    }
}
#endif